package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Menu;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/menu")


public class MenuController {
    @Autowired
    private MenuService menuService;

    //根据session获取用户，根据用户的角色查询对应的菜单，即不同角色对应的是不同的菜单
    @GetMapping("/findUnionMenu")
    public Result findMenu(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        //存储前端需要的menuList数据
        ArrayList<HashMap<String, Object>> parentList = new ArrayList<>();
        //前端需要的data数据
        HashMap<String, Object> frontHashMap = new HashMap<>();
        //存放查询出来的父菜单，用List存储，可能会有多个平级的角色
        List<Menu> parentMenu = new ArrayList<>();
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色id获取父菜单
            parentMenu = menuService.findParentMenu(roleId);
        }
        //
        for (Menu menu : parentMenu) {

            HashSet<HashMap<String, Object>> childHashSet = new HashSet<>();

            List<Menu> childMenu = null;
            for (Role role : roles) {
                //根据父菜单的id,和角色id,查询二级子菜单
                childMenu = menuService.findChildMenu(role.getId(), menu.getId());
            }
            for (Menu childMenuDatail : childMenu) {

                HashMap<String, Object> detailHashMap = new HashMap<>();
                //前端需要的格式
                detailHashMap.put("title", childMenuDatail.getName());
                detailHashMap.put("path", childMenuDatail.getPath());
                detailHashMap.put("linkUrl", childMenuDatail.getLinkUrl());
                childHashSet.add(detailHashMap);
            }
            HashMap<String, Object> objectHashMap = new HashMap<>();
            //前端需要的格式
            objectHashMap.put("title", menu.getName());
            objectHashMap.put("path", menu.getPath());
            objectHashMap.put("icon", menu.getIcon());
            objectHashMap.put("children", childHashSet);
            parentList.add(objectHashMap);
        }
        //前端需要的格式
        frontHashMap.put("username", user.getUsername());
        frontHashMap.put("menuList", parentList);
        return new Result(true, MessageConst.GET_MENU_SUCCESS, frontHashMap);
    }
}
